﻿using Masa.BuildingBlocks.Dispatcher.Events;
using Masa.Contrib.Dispatcher.IntegrationEvents;
using Masa.Contrib.Dispatcher.IntegrationEvents.Options;
using Microsoft.Extensions.DependencyInjection.Extensions;
using RabbitMQ.Client;

namespace Sckf.Contrib.Dispatcher.IntegrationEvents.RabbitMq
{
    public static class DispatcherOptionsExtensions
    {
        public static IDispatcherOptions UseRabbitMq(this IntegrationEventOptions options, RabbitMQConfig config)
        {
            ConnectionFactory factory = new ConnectionFactory()
            {
                HostName = config.HostName,
                UserName = config.UserName,
                Password = config.Password,
                Port = config.Port,
                VirtualHost = config.VirtualHost
            };

            var connection = factory.CreateConnection();

            options.Services.TryAddSingleton<IConnection>(connection);

            //todo: 注册 RabbitMq 信息
            options.Services.TryAddSingleton<IPublisher, Publisher>();
            return options;
        }
    }

    public record RabbitMQConfig
    {
        public string HostName { get; set; }

        public string UserName { get; set; }
         
        public string Password { get; set; }

        public int Port { get; set; }

        public string VirtualHost { get; set; } = "/";
    }
}
